<?php
namespace Home\Controller;
use Think\Controller;
//echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">';

class LuckydrawController extends Controller
{

	private $drawMod,$prizeMod, $resultsMod;
    public function __construct()
    {
        parent::__construct();

        $this->drawMod = M("Lucky_draw");
        $this->prizeMod = M("Lucky_prize");
        $this->resultsMod = M("Lucky_results");
        $this->users = M("Users");
        
    }

    public function index()
    {
        //当前 有效的 抽奖活动
        $draw = $this->drawMod->where('status=1')->find();

        $draw_id = $draw['id'];
        $res_log = $this->resultsMod->where('is_win != 0 && draw_id='.$draw_id)->select();

        $users = M("Users");

        //中奖用户名和奖品名称
        foreach($res_log as $key =>$value){
            //$user = $users->where('user_id='.$value['uid'])->getField('user_name');
            $user = $users->where('user_id='.$value['uid'])->getField('mobile_phone');
            $data[$key]['username'] = $this->hidtel($user);
//            $data[$key]['prize'] = $this->prizeMod->where('id='.$value['is_win'])->getField('prize');
            $data[$key]['prize'] = $value['result_described'];
        }
        $this->assign('data_log',$data);
        $this->assign('draw',$draw);
        $this->assign('id',$draw_id);
        $this->display();
    }

    //账号手机号替换*号
    public function hidtel($phone)
    {
        $IsWhat = preg_match('/(1[3578]{1}[0-9])[0-9]{4}([0-9]{4})/i',$phone); //固定电话
        if($IsWhat == 1){
            return  preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i','$1****$2',$phone);
        }else{
            return  substr_replace($phone,'****',2,4);
        }
    }

    //抽奖控制器
    public function choujiang()
    {
        $draw_id = I('get.id','');//活动ID
        $user_id = session('user_id') ? session('user_id') : 1;//会员ID

        /***************************验证********************************/
        $drawrs = $this->drawMod->where('id='.$draw_id)->find();//查询抽奖
        if(!$drawrs){
            $this->ajaxReturn(array('yes'=>"活动不存在或已删除",'v'=>-2));
            die();
        }

        if($drawrs['start_time'] > time() || $drawrs['end_time'] < time()){
            $this->ajaxReturn(array('yes'=>"活动未开始或已结束",'v'=>-3));
            die();
        }

        //验证可用 积分
        $user_points = $this->users->where('user_id='.$user_id)->getField('user_points');
        if($user_points < intval($drawrs['need_points'])){
            $this->ajaxReturn(array('yes'=>"你当前积分不够参与抽奖",'v'=>-4));
            die();
        }


        //获取当天的年份
        $y = date("Y");//获取当天的月份
        $m = date("m");//获取当天的号数
        $d = date("d");//将今天开始的年月日时分秒，转换成unix时间戳(开始示例：2015-10-12 00:00:00)
        $todayTime= mktime(0,0,0,$m,$d,$y);

        //检查当天用户的抽奖次数 超过或等于$drawrs['nums'] 为已用完
        $userlog = $this->resultsMod->where('draw_id = '.$draw_id.' && uid ='.$user_id .'&& add_time > '.$todayTime)->order('add_time desc')->select();
        if(count($userlog) >= intval($drawrs['nums'])){
            $this->ajaxReturn(array('yes'=>"你今天的抽奖次数已经用完",'v'=>-1));
            die();
        }
        


        /***************************验证 END********************************/



        /***************************抽奖********************************/
        //减积分
        $log_id = D('PointsLog')->other_change(5, $user_id, "积分抽奖", $drawrs['need_points']);

        $prize_arr = $this->prizeMod->where('draw_id='.$draw_id.' && remain_num !=0')->select();//找出剩下数量不为0的
        foreach ($prize_arr as $key => $val) {
            $vv = $val['odds'] / 100 * 10000 ;//几率除以100，乘以10000
            $arr[$key+1] = $vv;//抽奖从0开始循序，不允许存在空的$key
        }
        //print_r($arr);
        $proSum = array_sum($arr);//抽奖值字段总和
        //echo "抽奖值字段总和".$proSum."<br>";
        $shang = 10000-$proSum;//没有奖的概率
        //echo "没有奖的概率".$shang."<br>";
        //如果不到100%，则剩下的为无奖
        if($shang){
            $arr[] = $shang;
            $prize_arr[] = array(
                'prize'=>"元宵快乐（谢谢参与）",
                'odds' => $shang
            );
        }
        //print_r($prize_arr);
        


        $rid = $this->get_rand($arr); //根据概率获取奖项id
        //echo "根据概率获取奖项id:".$rid."<br>";
        //exit;

        /***************************抽奖 END********************************/

        /***************************结果拼接********************************/
        $res['r'] = $rid-1;
        $win = isset($prize_arr[$rid-1]['id']) ? $prize_arr[$rid-1]['id']:0;
        $rslog = $this->get_result($draw_id, $user_id, $prize_arr[$rid-1]['prize'], $win);//记录抽奖信息

        if($win) {
            //如果中奖了，减少奖品数量
            $this->prizeMod->where('id=' . $prize_arr[$rid - 1]['id'])->setDec('remain_num', 1);//数量减一
        }

        $res['yes'] = $prize_arr[$rid-1]['prize']; //中奖项
        $res['v'] = isset($prize_arr[$rid-1]['id']) ? $prize_arr[$rid-1]['id']:0 ;//是否中奖
        unset($prize_arr[$rid-1]); //将中奖项从数组中剔除，剩下未中奖项
        shuffle($prize_arr); //打乱数组顺序
        for($i=0;$i<count($prize_arr);$i++){
            $pr[] = $prize_arr[$i]['prize'];
        }
        $res['no'] = $pr;//没中奖的
//        echo json_encode($res);
//        dump($res);
        $this->ajaxReturn($res);

    }

    /**
     * 创建抽奖记录
     * @param $drawId 项目ID
     * @param $memberId 中奖会员ID
     * @param string $described 奖品描述
     * @param int $wining 是否中奖,奖品ID，未中为0
     * @return mixed
     */
    private function get_result($drawId,$uid,$described='',$wining=0)
    {
        $data['draw_id'] = $drawId;
        $data['uid'] = $uid;
        $data['result_described'] = $described;
        $data['is_win'] = $wining;
        $data['add_time'] = time();
        $res = $this->resultsMod->add($data);
        return $res;
    }

    /**
     * 抽奖算法
     * 一个几率数字的数组，数字int类型。
     * @param $proArr
     * @return int|string
     */
    private function get_rand($proArr) 
    {
        $result = '';

        //概率数组的总概率精度
        $proSum = array_sum($proArr);

        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);

        return $result;
    }

}